package org.ramoths.netcom.sessions;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.ramoths.netcom.outils.FluxEntreeObjet;
import org.ramoths.netcom.outils.FluxSortieObjet;
import org.ramoths.netcom.sessions.exceptions.CommunicationException;
import org.ramoths.netcom.sessions.exceptions.SerialisationException;

public class SessionObjet
{
	private final SessionMessage sessionMessage;
	
	public SessionObjet(SessionMessage sessionMessage)
	{
		this.sessionMessage = sessionMessage;
	}
	
	public void envoyer(Object objet) throws SerialisationException, CommunicationException
	{
		FluxSortieObjet fso = new FluxSortieObjet();
		ObjectOutputStream oos = null;
		try
		{
			oos = new ObjectOutputStream(fso);
			oos.writeObject(objet);
			oos.close();
		}
		catch (Exception ex)
		{
			if (oos != null)
				try { oos.close(); } catch (Exception exx) {}
			throw new SerialisationException("Erreur de sérialisation de l'objet!", ex);
		}
		sessionMessage.envoyer(fso.getDonnees());
	}
	
	public Object recevoir() throws CommunicationException
	{
		byte[] donnees = sessionMessage.recevoir();
		//
		FluxEntreeObjet feo = new FluxEntreeObjet(donnees);
		ObjectInputStream ois = null;
		Object r = null;
		try
		{
			ois = new ObjectInputStream(feo);
			r = ois.readObject();
			ois.close();
		}
		catch (Exception ex)
		{
			throw new CommunicationException("Erreur de désérialisation de l'objet!", ex);
		}
		//
		return r;
	}
	
	public void fermer()
	{
		sessionMessage.fermer();
	}
}
